package xj.graph2d;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;

import xj.graph2d.graph.GraphNode;

public class GraphView 
  extends SimpleDrawView 
  implements DrawShapeConstants {

  public GraphView(GraphDocument doc) {
    super(doc);
    graph = doc;
  }

  protected GraphView(GraphDocument doc, 
		      DrawAttr attr,
		      ArrowAttr headArrowAttr, 
		      ArrowAttr tailArrowAttr) {
    super(doc, attr, headArrowAttr, tailArrowAttr);
    graph = doc;
  }

  public GraphDocument getGraphDocument() {
    return graph;
  }

  public void paintCanvasGraphOnly(Graphics2D g2, 
				   Rectangle2D rect,
				   boolean printing, 
				   boolean thumbnail) {
    if (debug) {
      System.out.println("GraphView.paintCanvasGraphOnly(): rect=" + rect);
    }

    if (graph != null) {
      if (!printing && !thumbnail) {
	paintBackgroundAndGrid(g2, rect);

	super.paintCanvas(g2, rect, false, false);
      }

      DrawShape selected = graph.getSelectedShape();
      GraphNode selectedNode = graph.getSelectedNode();
      Iterator nodes = graph.nodes();
      while (nodes.hasNext()) {
	Object o = nodes.next();
	if (o != null && 
	    o != selectedNode && 
	    o instanceof DrawShape) {
	  DrawShape shape = (DrawShape) o;
	  if (shape.isVisible()) {
	    boolean visible = true;
	    if (rect != null) {
	      Rectangle2D r = shape.getRepaintRect();
	      if (!rect.intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight())) {
		visible = false;
	      }
	    }
	    if (visible) {
	      shape.drawShape(g2, (!printing && shape == selected) ? DRAW_SELECTED : DRAW_DEFAULT);
	    }
	  }
	}
      }

      Iterator edges = graph.edges();
      while (edges.hasNext()) {
	Object o = edges.next();
	if (o != null && o instanceof DrawShape) {
	  DrawShape shape = (DrawShape) o;
	  if (shape.isVisible()) {
	    boolean visible = true;
	    if (rect != null) {
	      Rectangle2D r = shape.getBounds();
	      if (!rect.intersects(r.getX(), r.getY(), r.getWidth() + 1, r.getHeight() + 1)) {
		visible = false;
	      }
	    }
	    if (visible) {
	      shape.drawShape(g2, (!printing && shape == selected) ? DRAW_SELECTED : DRAW_DEFAULT);
	    }
	  }
	}
      }

      if (selectedNode != null && 
	  selectedNode instanceof DrawShape) {
	DrawShape shape = (DrawShape) selectedNode;
	boolean visible = true;
	if (rect != null) {
	  Rectangle2D r = shape.getBounds();
	  if (!rect.intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight())) {
	    visible = false;
	  }
	}
	if (visible) {
	  shape.drawShape(g2, DRAW_DEFAULT);
	}
      }

    }
  }

  protected GraphDocument graph;

}
